class MatchPlayerView extends eui.Component implements  eui.UIComponent {


	private return_btn:eui.Image;
	private img_header:eui.Image;
	private lab_userID:eui.Label;

	private room_id:eui.Label;
	 private player1_label:eui.Label;
	 private player2_label:eui.Label;
	 private player3_label:eui.Label;

	private player1_name:eui.Label;
	private player2_name:eui.Label;
	private player3_name:eui.Label;

	private player2_btn:eui.Button;
	private player3_btn:eui.Button;

    private player1_rect:eui.Rect;
	private player2_rect:eui.Rect;
	private player3_rect:eui.Rect;

	private player1_isowner: eui.Image;

	private start_btn:eui.Button;


	public  _playerList:Array<GameUser> = [];
	private _isInRoom:boolean = false;

    private joinFlag:number = 1;
	private joinInfo:any;

    private _roomID:string = "";
    private isOwner:boolean = false;
     private canStartGame:boolean = false;

    private default_name = "待加入";
	private default_rect_color = 0x555555;


	public static JOINFLAG ={
        RANDROOM:1,
        CREATEROOM:2,
        WITHROOMID:3,
        WITHPROPERTY:4
    }


	public constructor() {
		super();
        this.addMsResponseListen();
       
	}

	protected partAdded(partName:string,instance:any):void	{
		this.getChilds(partName,instance);
		super.partAdded(partName,instance);
	}


	protected childrenCreated():void {
		super.childrenCreated();
        this.joinRoom(this.joinFlag, this.joinInfo);
	}
	private getChilds(partName:string,instance:any):void{
		switch(partName){
			case "room_id":
				this.room_id = instance;
				break;
			case "start_btn":
				this.start_btn = instance;
			//	this.lab_joinRandRoom.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onButtonClickCreateRoom, this);
				break;
			case "player1_name":
				this.player1_name = instance;
				break;
			case "player2_name":
				this.player2_name = instance;
				break;
			case "player3_name":
				this.player3_name = instance;
				break;
            case "player1_label":
				this.player1_label = instance;
				break;
            case "player2_label":
				this.player2_label = instance;
				break;
            case "player3_label":
				this.player3_label = instance;
				break;
			case "player1_isowner":
				this.player1_isowner = instance;
				this.player1_isowner.visible = false;
				break;
			case "player2_btn":
				this.player2_btn = instance;
				this.player2_btn.visible = false;
				this.player2_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnKickPlayerClick, this);
				break;
			case "player3_btn":
				this.player3_btn = instance;
				this.player3_btn.visible = false;
				this.player3_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnKickPlayerClick, this);
				break;
			case "player1_rect":
				this.player1_rect = instance;
				this.player1_rect.fillColor = 0x79797C;
				break;
            case "player2_rect":
				this.player2_rect = instance;
				this.player2_rect.fillColor = 0x79797C;
				break;
			case "player3_rect":
				this.player3_rect = instance;
				this.player3_rect.fillColor = 0x79797C;
				break;
			case "img_header":
				this.img_header = instance;
				this.img_header.source = GameData.gameUser.avatar;
				break;
			case "lab_userID":
				this.lab_userID = instance;
				this.lab_userID.text ="用户："+GameData.gameUser.id+"\n"+GameData.gameUser.name;
				break;
			case "return_btn":
                this.return_btn = instance;
                this.return_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.mbuttonLeaveRoom, this);
			default:
				break;
		}
	}
    public setJoinParame(flag:number, info?:any){
		this.joinFlag = flag;
		this.joinInfo = info;
	}
    /**
	 * 加入房间的统一入口
	 */
	public joinRoom(flag:number, info:any){
        this.joinFlag = flag;
        if(flag == 1){
            //this.lab_matchmode.text = "（随机匹配）";
            this.joinRandRoom();
        }else if(flag == 2){
            //this.createRoom();
        }else if(flag == 3){
            //this.joinWithRoomID(info);
           // this.lab_matchmode.text = "";
        }else if(flag == 4){
            if(GameData.syncFrame){
               // this.lab_matchmode.text = "（帧同步匹配）";
                info = {"match":"frameSync"}
            }else{
                //this.lab_matchmode.text = "（自定义属性匹配）";
            }
           // this.joinRoomWithPro(info);
        }
    }
     /**
     * 随机加入房间
     */
    private joinRandRoom(){
        let userPro:string = JSON.stringify({name:GameData.gameUser.name, avatar:GameData.gameUser.avatar});
        mvs.MsEngine.getInstance.joinRandomRoom(GameData.maxPlayerNum,userPro);
    }
    /**
     * 加入房间回调
     * @param {egret.Event} event
     */
    private joinRoomResponse(event:egret.Event) {
        console.log("joinRoomResponse,event:" + event);
		let data = event.data;
        if(data.status == 200){
			this.room_id.text = "房间号:" + data.roomInfo.roomID;
			this._roomID = data.roomInfo.roomID;
            GameData.roomID = data.roomInfo.roomID;
			this._isInRoom = true;
            
            GameData.gameUser.isOwner = false;
            //房主
            if(data.roomInfo.ownerId == GameData.gameUser.id){
                this.isOwner = true;
            }else{
                this.isOwner = false;
            }

            //地图
            // if(data.roomInfo.roomProperty === GameData.roomPropertyType.mapB){
            //     GameData.roomPropertyValue = GameData.roomPropertyType.mapB
            //     this.rad_mapB.selected = true;
            // }else{
            //     GameData.roomPropertyValue = GameData.roomPropertyType.mapA
            //     this.rad_mapA.selected = true;
            // }


			let tableID:number =  1;
            //显示我自己的信息
            this.addPlayerList(GameData.gameUser.id, GameData.gameUser.name, GameData.gameUser.avatar, tableID, this.isOwner);

            //如果房间有其他人就显示别人信息
            let userList:Array<any> = data.userList;
            for(let i = 0; i < userList.length; i++){
                tableID++;
                this.otherJoinShowInfo(userList[i].userId, tableID, userList[i].userProfile, data.roomInfo.ownerId == userList[i].userId);
            }
            this.checkStart();
        }else{
            console.info("加入房间失败",data);
        }
    }
    private checkStart(){
        console.info("房间人数："+this._playerList.length);
        if(this._playerList.length == GameData.maxPlayerNum){
            console.info("可以开始游戏");
            this.canStartGame = true;
            //this.check_closeRoom.visible = false;
            if(this.joinFlag == MatchPlayerView.JOINFLAG.CREATEROOM || this.joinFlag == MatchPlayerView.JOINFLAG.WITHROOMID){
                this.start_btn.visible = this.isOwner;
                this.start_btn.enabled = this.isOwner;
            }else{
                if(this.isOwner){
                    mvs.MsEngine.getInstance.joinOver("人满开始游戏");
                }
                this.start_btn.visible = false;
                this.start_btn.enabled = false;
                
            }
        }else{
            this.canStartGame = false;
            this.start_btn.enabled = false;
            //this.check_closeRoom.visible = true;
        }
    }
    /**
     * 显示其他玩家 加入房间 信息
     * @param userID 
     * @param tableID 
     * @param userProfile 
     */
    private otherJoinShowInfo(userID:number, tableID:number, userProfile:string, owner:boolean = false){
        if(userProfile && userProfile !== ""){
            let name = "";
            let avatar = "";
            let userInfo = JSON.parse(userProfile);
            if(userInfo.name){
                name = userInfo.name;
            }
            if(userInfo.avatar){
                avatar = userInfo.avatar;
            }
            this.addPlayerList(userID, name, avatar, tableID, owner);
        }
    }
    /**
     * 
     * @param id 
     * @param name 
     * @param avator 
     * @param tableID 
     */
    private addPlayerList(id:number,name:string,avatar:string, tableID:number, owner:boolean = false):GameUser{
        let play:GameUser = new GameUser();
        play.id = id;
        play.name = name;
        play.avatar = avatar;
        play.tableID = tableID;
        play.isOwner = owner;
        this._playerList.push(play);
        this.showPlayer(play);
        return play;
    }
    /**
     * 显示用户信息
     * @param player 
     */
    private showPlayer(player:GameUser){
        
        let tableID:number = player.tableID;
        if(this.joinFlag == MatchPlayerView.JOINFLAG.CREATEROOM || this.joinFlag == MatchPlayerView.JOINFLAG.WITHROOMID){
            // this.group_map.visible = true;
            // this.rad_mapA.enabled = this.isOwner;
            // this.rad_mapB.enabled = this.isOwner;
            // console.log("mapValue:",this.rad_mapA.value);
            // console.log("mapValue:",this.rad_mapB.value);
            this.start_btn.visible = this.isOwner;
            this.player1_isowner.visible = this.isOwner;
            if(tableID == 2 || tableID == 3){
                this["player"+tableID + "_btn"].visible = this.isOwner;
            }
        }else{
			this.start_btn.visible = false;
           // this.group_map.visible = false;
		}

        // this.check_closeRoom.visible = !this.canStartGame;
        // this.check_closeRoom.enabled = this.isOwner;

		this["player"+tableID + "_label"].text = tableID.toString();
		this["player"+tableID + "_label"].textColor = 0xffffff;
		if(player.id == GameData.gameUser.id){
			this["player"+tableID + "_label"].text = "我";
		}
		
        if(tableID == 1){
           // this.rect_player1.fillColor = 0x8BD7E0;
            this.player1_name.text = player.name;
        }else if(tableID == 2){
            this.player2_rect.fillColor = 0x96E8B5;
            this.player2_name.text = player.name;
        }else if(tableID == 3){
            this.player3_rect.fillColor = 0xE8CE90;
            this.player3_name.text = player.name;
        }
    }
    /**
     * 加入房间异步回调事件
     */
    private joinRoomNotify(ev:egret.Event) {
        let data = ev.data;
        let userID = data.userId;
        let tableID = this._playerList.length + 1;
        this.otherJoinShowInfo(data.userId, tableID, data.userProfile, data.userId == data.owner);
        this.checkStart();
    }
	/**
     * 退出房间
     */
    private mbuttonLeaveRoom(event: egret.TouchEvent) {
        //如果没有进入房间成功就直接返回游戏大厅界面
        if (this._isInRoom) {
            mvs.MsEngine.getInstance.leaveRoom("累了困了离开一下");
        } else {
            this.release();
            //退出房间成功进入游戏大厅
            GameSceneView._gameScene.lobby();
        }

    }
	//踢人
	private btnKickPlayerClick(e:egret.TouchEvent){
        let tableid = 0;
        if(e.target.name == "btn_kick2"){
            tableid = 2;
        }else if(e.target.name == "btn_kick3"){
            tableid = 3;
        }
        let user:GameUser = this.getUserForTableID(tableid);
        if(user == null){
            console.info("用户不存在");
            return;
        }
        mvs.MsEngine.getInstance.kickPlayer(user.id, "我们不能一起好好的玩游戏");
    }
	private getUserForTableID(tableid:number):GameUser{
        let user:GameUser = null;
        this._playerList.forEach((p)=>{
            if(p.tableID == tableid){
                user = p;
            }
        });
        return user;
    }
	
    /**
     * 关闭房间回调事件
     */
    private joinOverResponse(ev:egret.Event) {
        let rsp = ev.data;
        if (rsp.status === 200) {
            console.log("关闭房间成功");
            if(this.canStartGame){
                //开始游戏
                this.notifyGameStart();
                GameData.playerUserIds = this._playerList;
                return;
            }
        } else {
            console.log("关闭房间失败，回调通知错误码：", rsp.status);
        }
        Toast.show(" 设置不允许房间加人 " + (rsp.status == 200 ? "success" : "fail"));
        //this.check_closeRoom.selected = ((rsp.status == 200)?false:this.check_closeRoom.selected);
    }
   /**
     * 开始游戏
     */
    private notifyGameStart() {
        GameData.isRoomOwner = true;
        let arrs = [];
        this._playerList.forEach((element)=>{
            arrs.push({id:element.id,name:element.name,avatar:element.avatar});
        });

        let event = {
            action: GameData.gameStartEvent,
            userIds: arrs
        };

        /**
         * 发送开始游戏消息
         */
        let result = mvs.MsEngine.getInstance.sendEvent(JSON.stringify(event));
        if (result.result !== 0){
            return console.log('发送游戏开始通知失败，错误码' + result.result);
        }
        
        // 发送的事件要缓存起来，收到异步回调时用于判断是哪个事件发送成功
        GameData.events[result.sequence] = event;
        console.log("发起游戏开始的通知，等待回复");
    }
     private sendEventResponse(ev:egret.Event) {
        let rsp = ev.data;
        if (rsp.status !== 200) {
            return console.log('事件发送失败,status:' + status);
        }

        var event = GameData.events[rsp.sequence]

        if (event && event.action === GameData.gameStartEvent) {
            delete GameData.events[rsp.sequence];
            this.release();
            GameSceneView._gameScene.play();
        }
    }

    private sendEventNotify(ev:egret.Event) {
        console.log("收到消息", ev.data);
        let sdnotify = ev.data;
        if (sdnotify
            && sdnotify.cpProto
            && sdnotify.cpProto.indexOf(GameData.gameStartEvent) >= 0) {
            GameData.playerUserIds = this._playerList;
            this.release();
            GameSceneView._gameScene.play();
        }
    }
    /**
     * 关闭房间异步回调
     */
    private joinOverNotify(ev:egret.Event) {
        let notifyInfo = ev.data;
        console.log("userID:" + notifyInfo.userID + " 关闭房间：" + notifyInfo.roomID + " cpProto:" + notifyInfo.cpProto);
        Toast.show(notifyInfo.userID + " 设置了不允许房间加人");
       // this.check_closeRoom.selected = false;
       // this.check_closeRoom.label = "禁止加入";
    } 
/**
     * 他人离开房间回调
     */
    private leaveRoomNotify(ev:egret.Event) {
		let data = ev.data;
        console.info("玩家离开",data)
        let userID:number = data.userId;

        /**
         * 是否房主有变动，有变动的话就转移房主
         */
        if(data.owner == GameData.gameUser.id){
            this.isOwner = true;
        }else{
            this.isOwner = false;
        }

        //删除该用户
        this.delPlayerList(userID);
        this.canStartGame = false;
        for(let i = 0; i < this._playerList.length; i++){
            if(data.owner == this._playerList[i].id){
                this._playerList[i].isOwner = true;
            }else{
                this._playerList[i].isOwner = false;
            }
            //重置用户位置并重新显示
            this._playerList[i].tableID = i+1;
            this.showPlayer(this._playerList[i]);
        }
    }
    /**
     * 删除用户列表
     * @param id 
     */
    private delPlayerList(id:number){
        let player:GameUser = new GameUser();
        let arr:Array<GameUser> = [];
        for(let i = 0; i < this._playerList.length; i++){
            
            if(this._playerList[i].id == id){
                player.id = this._playerList[i].id;
                player.avatar = this._playerList[i].avatar;
                player.name = this._playerList[i].name;
                player.tableID = this._playerList[i].tableID;
                this._playerList.splice(i,1);
                this.wipePlayer(player);
            }
        }
    }
    /**
     * 擦除用户信息
     * @param player 
     */
    private wipePlayer(player:GameUser){
        let tableID:number = player.tableID;
        if(tableID == 1){
            this.player1_name.text = this.default_name;
			this.player1_rect.fillColor = this.default_rect_color;
			this.player1_label.text = "1";
			this.player1_label.textColor = 0x757575;

            this.player2_name.text = this.default_name;
			this.player2_rect.fillColor = this.default_rect_color;
			this.player2_label.text = "2";
			this.player2_label.textColor = 0x757575;

            this.player3_name.text = this.default_name ;
			this.player3_rect.fillColor = this.default_rect_color;
			this.player3_label.text = "3";
			this.player3_label.textColor = 0x757575;
			
            // this.btn_kick1.visible = false;
            this.player2_btn.visible = false;
            this.player3_btn.visible = false;
            
        }else if(tableID == 2){
            this.player2_name.text = this.default_name;
			this.player2_rect.fillColor = this.default_rect_color;
			this.player2_label.text = "2";
			this.player2_label.textColor = 0x757575;

            this.player3_name.text = this.default_name ;
			this.player3_rect.fillColor = this.default_rect_color;
			this.player3_label.text = "3";
			this.player3_label.textColor = 0x757575;
			
            // this.btn_kick1.visible = false;
            this.player2_btn.visible = false;
            this.player3_btn.visible = false;
        }else if(tableID == 3){
            this.player3_name.text = this.default_name ;
			this.player3_rect.fillColor = this.default_rect_color;
			this.player3_label.text = "3";
			this.player3_label.textColor = 0x757575;
			
            // this.btn_kick1.visible = false;
            this.player3_btn.visible = false;
        }
        this.player1_isowner.visible = false;
		
		
    }

    /**
     * 自己离开房间回调
     */
    private leaveRoomResponse(ev:egret.Event) {
        let rsp = ev.data;
        if (rsp.status !== 200) {
            console.log("退出房间失败！status=" + rsp.status);
        } else {
            this.release();
            //退出房间成功进入游戏大厅
            GameSceneView._gameScene.lobby();
        }
    }
	/**
     * 注册监听
     */
    private addMsResponseListen(){
        // //加入房间
         mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_JOINROOM_RSP, this.joinRoomResponse,this);
         mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_JOINROOM_NTFY, this.joinRoomNotify,this);

         //关闭房间
         mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_JOINOVER_NTFY, this.joinOverNotify,this);
         mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_JOINOVER_RSP, this.joinOverResponse,this);

        // //打开房间
        // mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_JOINOPEN_RSP, this.joinOpenResponse,this);
        // mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_JOINOPEN_NTFY, this.joinOpenNotify,this);

        // //发送消息
         mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_SENDEVENT_RSP, this.sendEventResponse,this);
         mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_SENDEVENT_NTFY, this.sendEventNotify,this);

         //离开房间
         mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_LEAVEROOM_RSP, this.leaveRoomResponse,this);
         mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_LEAVEROOM_NTFY, this.leaveRoomNotify,this);

        // //创建房间事件
        // mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_CREATEROOM_RSP,this.createRoomResponse, this);

        // //踢人事件
        // mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_KICKPLAYER_RSP, this.kickPlayerResponse,this);
        // mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_KICKPLAYER_NTFY, this.kickPlayerNotify,this);

        // //设置帧同步
        // mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_NETWORKSTATE_NTFY,  this.networkStateNotify,this);

        // //设置房间属性
        // mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_SETROOMPROPERTY_RSP, this.setRoomPropertyResponse,this);
        // mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_SETROOMPROPERTY_NTFY, this.setRoomPropertynotify,this);
    }

    /**
     * 取消监听
     */
    public release(){
         mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_JOINROOM_RSP, this.joinRoomResponse,this);
         mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_JOINROOM_NTFY, this.joinRoomNotify,this);

         mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_JOINOVER_NTFY, this.joinOverNotify,this);
         mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_JOINOVER_RSP, this.joinOverResponse,this);

         mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_SENDEVENT_RSP, this.sendEventResponse,this);
         mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_SENDEVENT_NTFY, this.sendEventNotify,this);

        // mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_JOINOPEN_RSP, this.joinOpenResponse,this);
        // mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_JOINOPEN_NTFY, this.joinOpenNotify,this);

         //离开房间
         mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_LEAVEROOM_RSP, this.leaveRoomResponse,this);
         mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_LEAVEROOM_NTFY, this.leaveRoomNotify,this);

        // //创建房间事件
        // mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_CREATEROOM_RSP,this.createRoomResponse, this);

        // //踢人事件
        // mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_KICKPLAYER_RSP, this.kickPlayerResponse,this);
        // mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_KICKPLAYER_NTFY, this.kickPlayerNotify,this);

        // //设置帧同步
        // mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_NETWORKSTATE_NTFY,  this.networkStateNotify,this);

        // //设置房间属性
        // mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_SETROOMPROPERTY_RSP, this.setRoomPropertyResponse,this);
        // mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_SETROOMPROPERTY_NTFY, this.setRoomPropertynotify,this);
    }
}